<!-- src/components/SliderCaptcha.vue -->
<template>
  <div class="captcha-container">
    <div v-if="!verified" class="slider-captcha">
      <!-- 背景图片区域 -->
      <div class="captcha-background">
        <img :src="captchaData.background_image" alt="Captcha Background" class="background-image" />

        <!-- 显示滑块图片 -->
        <img
            :src="captchaData.slider_image"
            alt="Slider"
            class="slider-image-on-bg"
            :style="{ left: (sliderTrackPosition - 25) + 'px', top: '60px' }"
        />
      </div>

      <!-- 滑动轨道和滑块 -->
      <div class="slider-area">
        <div class="slider-track" ref="trackRef">
          <div
              class="slider-handle"
              @mousedown="onMouseDown"
              @touchstart="onTouchStart"
              :style="{ left: sliderTrackPosition + 'px' }"
          >
            <span class="slider-arrow">→</span>
          </div>
        </div>
      </div>

      <!-- 状态提示 -->
      <div class="status-info">
        <div v-if="errorDistance <= 15" class="status-success">
          ✅ 位置正确，请验证
        </div>
        <div v-else class="status-hint">
          请拖动滑块到正确位置
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <button @click="refreshCaptcha" class="refresh-btn">
          <span class="refresh-icon">🔄</span>
          刷新验证码
        </button>
        <button @click="verifyCaptchaPosition" class="verify-btn"
                :disabled="errorDistance > 15">
          验证
        </button>
      </div>
    </div>

    <!-- 验证成功提示 -->
    <div v-else class="verification-success">
      ✅ 验证成功！
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { getSliderCaptcha, verifyCaptcha } from '@/api/captcha'

const emits = defineEmits(['verified'])

// 数据绑定
const captchaData = ref({
  background_image: '',
  slider_image: '',
  token: '',
  slider_width: 50,
  correct_position: 0
})

// 位置相关
const sliderTrackPosition = ref(0)
const isDragging = ref(false)
const verified = ref(false)
const trackRef = ref(null)

// 计算属性
const correctPosition = computed(() => {
  return captchaData.value.correct_position || 0
})

const errorDistance = computed(() => {
  return Math.abs(sliderTrackPosition.value - correctPosition.value)
})

/**
 * 刷新验证码
 */
const refreshCaptcha = async () => {
  try {
    const response = await getSliderCaptcha()

    if (response.data) {
      captchaData.value = response.data
      sliderTrackPosition.value = 0
      verified.value = false
      isDragging.value = false
    } else {
      throw new Error('无效的响应数据')
    }
  } catch (error) {
    console.error('加载验证码失败:', error)
    alert('验证码加载失败，请重试')
    setTimeout(refreshCaptcha, 1000)
  }
}

/**
 * 开始拖动
 */
const onMouseDown = (e) => {
  e.preventDefault()
  isDragging.value = true
  document.addEventListener('mousemove', onMouseMove)
  document.addEventListener('mouseup', onMouseUp)
}

const onTouchStart = (e) => {
  e.preventDefault()
  isDragging.value = true
  document.addEventListener('touchmove', onTouchMove)
  document.addEventListener('touchend', onTouchEnd)
}

/**
 * 更新滑块位置
 */
const updateSliderPosition = (clientX) => {
  if (!trackRef.value) return

  const trackRect = trackRef.value.getBoundingClientRect()
  const handleWidth = 50

  // 计算滑块位置
  let newPosition = clientX - trackRect.left

  // 限制在轨道范围内 (0-250px)
  const maxTrackPosition = 250
  newPosition = Math.max(0, Math.min(newPosition, maxTrackPosition))

  sliderTrackPosition.value = Math.round(newPosition)
}

/**
 * 拖动中
 */
const onMouseMove = (e) => {
  if (!isDragging.value) return
  updateSliderPosition(e.clientX)
}

const onTouchMove = (e) => {
  if (!isDragging.value) return
  updateSliderPosition(e.touches[0].clientX)
}

/**
 * 停止拖动
 */
const onMouseUp = () => {
  endDrag()
}

const onTouchEnd = () => {
  endDrag()
}

const endDrag = () => {
  if (!isDragging.value) return
  isDragging.value = false
  document.removeEventListener('mousemove', onMouseMove)
  document.removeEventListener('mouseup', onMouseUp)
  document.removeEventListener('touchmove', onTouchMove)
  document.removeEventListener('touchend', onTouchEnd)
}

/**
 * 验证滑块位置
 */
const verifyCaptchaPosition = async () => {
  try {
    const response = await verifyCaptcha({
      token: captchaData.value.token,
      user_offset: sliderTrackPosition.value,
      tolerance: 15
    })

    if (response.data && response.data.success) {
      verified.value = true
      emits('verified', captchaData.value.token)
    } else {
      throw new Error(response.data?.message || '验证失败')
    }
  } catch (error) {
    console.error('验证失败:', error)
    let errorMessage = error.message || '验证失败，请重试'

    if (error.response?.data?.debug_info) {
      errorMessage = `验证失败，请重新尝试`
    }

    alert(errorMessage)
    refreshCaptcha()
  }
}

/**
 * 获取当前滑块位置
 */
const getCurrentPosition = () => {
  return sliderTrackPosition.value
}

/**
 * 页面加载完成后自动刷新验证码
 */
onMounted(() => {
  refreshCaptcha()
})

defineExpose({
  refreshCaptcha,
  getCurrentPosition  // 暴露获取位置的方法
})
</script>

<style scoped>
.captcha-container {
  max-width: 320px;
  margin: 0 auto;
}

.slider-captcha {
  background: white;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0,0,0,0.1);
}

/* 背景图片区域 */
.captcha-background {
  position: relative;
  width: 100%;
  height: 150px;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 20px;
  border: 2px solid #e1e5e9;
}

.background-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 滑块图片在背景上的显示 */
.slider-image-on-bg {
  position: absolute;
  width: 50px;
  height: 30px;
  pointer-events: none;
  z-index: 3;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.3);
  transition: left 0.1s ease;
}

/* 滑动区域 */
.slider-area {
  margin-bottom: 15px;
}

.slider-track {
  width: 300px;
  height: 40px;
  background: #f8f9fa;
  border-radius: 20px;
  margin: 0 auto;
  position: relative;
  cursor: pointer;
  border: 2px solid #dee2e6;
}

.slider-handle {
  width: 50px;
  height: 40px;
  background: linear-gradient(135deg, #1890ff, #096dd9);
  border-radius: 20px;
  position: absolute;
  top: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: bold;
  user-select: none;
  cursor: grab;
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);
  transition: all 0.1s;
  z-index: 20;
}

.slider-handle:active {
  cursor: grabbing;
  transform: scale(1.05);
}

.slider-arrow {
  font-size: 18px;
}

/* 状态信息 */
.status-info {
  text-align: center;
  margin-bottom: 15px;
  min-height: 20px;
}

.status-success {
  color: #28a745;
  font-size: 14px;
  font-weight: 600;
}

.status-hint {
  color: #6c757d;
  font-size: 14px;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  gap: 12px;
}

.refresh-btn, .verify-btn {
  flex: 1;
  padding: 12px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 600;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
}

.refresh-btn {
  background: #6c757d;
  color: white;
}

.refresh-btn:hover {
  background: #5a6268;
  transform: translateY(-1px);
}

.verify-btn {
  background: #28a745;
  color: white;
}

.verify-btn:hover:not(:disabled) {
  background: #218838;
  transform: translateY(-1px);
}

.verify-btn:disabled {
  background: #ced4da;
  color: #6c757d;
  cursor: not-allowed;
  transform: none;
}

/* 验证成功提示 */
.verification-success {
  text-align: center;
  color: #28a745;
  font-size: 16px;
  font-weight: 600;
  padding: 30px;
  background: #d4edda;
  border: 2px solid #c3e6cb;
  border-radius: 10px;
}

.refresh-icon {
  font-size: 16px;
}
</style>